package psn.james.kaixin.util;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.Charset;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XMLParser {

	private DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	private DocumentBuilder db;
	private Document doc;

	public XMLParser(String xml, Charset charset) throws ParserConfigurationException, SAXException, IOException {
		super();
		db = dbf.newDocumentBuilder();
		doc = db.parse(new ByteArrayInputStream(xml.getBytes(charset)));
	}
	
	public NodeList getNodeList(String path){
		String[] nodeNames = path.split("/");
		return parse(doc, nodeNames, 1);
	}
	
	public String getNodeValue(String path){
		try {
			return getNodeList(path).item(0).getTextContent();
		} catch (Exception e) {
		
		}
		return "";
	}
	
	private NodeList parse(Node root, String[] nodeNames, int level){
		NodeList nodeList = root.getChildNodes();
		if (level == nodeNames.length)
			return nodeList;
		for (int i = 0; i < nodeList.getLength(); i++){
			if (nodeList.item(i).getNodeName().equals(nodeNames[level])){
				return parse(nodeList.item(i), nodeNames, ++level);
			}
		}		
		return null;
	}
}